let aliyun = require('./aliyun')
let { getIpFormChinaz, getIpFormHans } = require('./getIp')

// TODO 替换成自己的。【创建 ACCESS KEY 方法：https://help.aliyun.com/zh/ram/user-guide/create-an-accesskey-pair?spm=a2c4g.11186623.0.i2】
process.env['ALIBABA_CLOUD_ACCESS_KEY_ID'] = 'LTAI5tPSyRV1xnSVp36VJjFs';
process.env['ALIBABA_CLOUD_ACCESS_KEY_SECRET'] = 'JYjEu1Xwv2sfPsOrSqsxtLStlK2n1z';

let localIp; // 本机ip
let targetIp; // target.wuweijun.fun 指定的ip
let recordId; // target.wuweijun.fun 对应的recordId

// 获取到当前服务器真实ip地址
function getIp(callback) {
  return new Promise((resolve, reject) => {
    getIpFormHans().then(res => {
      if (res) {
        console.log(new Date(), '本机ip', res)
        localIp = res;
        resolve()
      } else reject();
    })
  })
}

// 调用阿里云API，查看指定的域名详情
function describeSub() {
  return new Promise((resolve, reject) => {
    aliyun.describeSub({
      // TODO 更改为自己的域名
      subDomain: 'target.wuweijun.fun'
    }).then(res => {
      // console.log(`describeSub statusCode`, res.statusCode)
      // console.log(`describeSub body.domainRecords`, res.body.domainRecords)
      // console.log(`describeSub res.body.domainRecords.record`, res.body.domainRecords.record)
      if (res.statusCode == 200 && res.body.domainRecords && res.body.domainRecords.record.length > 0) {
        targetIp = res.body.domainRecords.record[0].value;
        recordId = res.body.domainRecords.record[0].recordId;
      }
      resolve()
    })
  })
}

// 调用阿里云API，删除指定的域名
function deleteFn(callback) {
  return new Promise((resolve, reject) => {
    if (!recordId) { resolve(); return; };
    aliyun.deleteFn({
      recordId: recordId,
    }).then(res => {
      // console.log(`deleteFn res.statusCode`, res.statusCode)
      // console.log(`deleteFn res.body`, res.body)
      if (res.statusCode == 200) {
        resolve()
      }
    })
  })
}

// 调用阿里云API，添加指定的域名
function add() {
  if (!localIp) return;
  // TODO 这是新增一个域名记录，具体参数看这里【添加解析记录：https://api.aliyun.com/api/Alidns/2015-01-09/AddDomainRecord】
  aliyun.add({
    domainName: 'wuweijun.fun',
    RR: 'target',
    type: "A",
    value: localIp,
  }).then(res => {
    // console.log(`add res`, res)
    // console.log(`add res.statusCode`, res.statusCode)
    // console.log(`add res.body`, res.body)
    if (res.statusCode == 200) {
      console.log(`设置新的ip记录值 - 成功，ip为：${localIp}`,)
    } else {
      console.log(`设置新的ip记录值 - 失败！！`,)
    }
  })
}

let total = 0;
function start() {
  getIp().then(() => {
    total++;
    if (targetIp && localIp && targetIp == localIp) { if (total % 12 != 0) { return; } }
    describeSub().then(() => {
      console.log(`
        域名对应的ip：${targetIp}

        本机ip：${localIp}
      `)
      if (localIp && targetIp != localIp) {
        deleteFn().then(() => {
          add()
        })
      } else {
      }
    })
  })
}

// 一切的开始。
start();
setInterval(() => {
  start();
}, 1000 * 60 * 30);